﻿/* $RCSFile: InterviewUtil.cs $
 * Copyright (C) Addon Nice Technologies 2010
 * $Source: ?/Addon Nice/AddonNice/AddonNice.LeadProspection/PageModules/Interview/InterviewUtil.cs $
 * $log$
 * Revision 11 2010/08/09 10:18:24  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;

using AddonNice.Configuration;
using AddonNice.CRMWrapper;
using AddonNice.Diagnostics;
using AddonNice.UI.DataTypes;
using AddonNice.Settings;
using AddonNice.LeadProspection.Settings;

using Trace2    =   System.Diagnostics.Trace;
using Cache2    =   AddonNice.Settings.Cache.CurrentCache;

namespace AddonNice.PageModules.Interview
{
    #region Local TraceSwitch 
	
    public class InterviewTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	=	new ADNTraceSwitch("InterviewTrace","Special Trace Switch for Interview");
	}
	#endregion Local TraceSwitch 

    public class InterviewUtil
    {
        #region public locals

        Guid _EntityID                          =   Guid.Empty;
        /// <summary>
        /// Reset profile on SET
        /// </summary>
        public Guid EntityID
        {
            get
            {
                return _EntityID;
            }
            set
            {
                if ( value != Guid.Empty )
                {
                    ADNDynInterview dynI   =   DynEntity.GetFromCache<ADNDynInterview>(PStr.interview,Wrapper,ResetWrapper,value);
                    if ( dynI.Retrieved )
                        CallingProfile      =   dynI.callingprofile;
                    _EntityID               =   value;
                }
			    if (InterviewTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CalloutCampaignUtil EntityID SET _EntityID: {0}, CallingProfile: {1}",_EntityID,CallingProfile),InterviewTrace.Sw.Info);
            }
        }

        public int CallingProfile               =   1;
        public int CacheDelay                   =   30;
        public CRMWrapperBase Wrapper           =   null;
        public ResetWrapperHandler ResetWrapper =   null;

        SettingsDictionary _cSettings   =   null;
        public SettingsDictionary cSettings
        {
            get
            {
                if ( _cSettings == null )
                    _cSettings  =           GetAllProjectItems();
                return _cSettings;
            }
        }
            

        SortedList<string,ADNDynProjectItemValue>   _PValuesList =   null;
        public SortedList<string,ADNDynProjectItemValue> PValuesList
        {
            get
            {
                if ( _PValuesList == null  )
                {
                    GetAllProjectItems();
                }
                return _PValuesList;
            }
        }
        
        SortedList<string,ADNDynProjectItem> _PItemLst           =   null;
        public SortedList<string,ADNDynProjectItem> PItemLst 
        {
            get
            {
                if ( ( _PItemLst == null ) /*|| ( _PItemLst.Count == 0 )*/ )
                {
                    GetAllProjectItems();
                }
                return _PItemLst;
            }
        }
        #endregion public locals

        public InterviewUtil(CRMWrapperBase Wrap,ResetWrapperHandler ResetWrap,Guid EntID,int cacheDelay)
        {
            Wrapper         =   Wrap;
            ResetWrapper    =   ResetWrap;
            EntityID        =   EntID; // must stay after wrappers init
            CacheDelay      =   cacheDelay;
         }

        
        public SettingsDictionary GetAllProjectItems()
        {
			if (InterviewTrace.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]InterviewUtil GetAllProjectItems BEG.",ModuleTraceSwitch.Sw.Info);
            try
            {
                Guid InterviewId                    =   EntityID;
			    if (InterviewTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]InterviewUtil GetAllProjectItems InterviewId: {0}",InterviewId),InterviewTrace.Sw.Info);
                Guid SelectedGuid                   =   Guid.Empty;
                string CKey                         =   string.Format("ProjectitemLst_{0}",CallingProfile);
                if ( Cache2.Exists(CKey) )
                {   
                    _PItemLst                       =   (SortedList<string,ADNDynProjectItem>)Cache2.Get(CKey);
			        if (InterviewTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]InterviewUtil GetAllProjectItems found in cache_PItemLst.Count: {0}",_PItemLst.Count),InterviewTrace.Sw.Info);
                }
                else
                {
			        if (InterviewTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]InterviewUtil GetAllProjectItems CallingProfile: {0}",CallingProfile),InterviewTrace.Sw.Info);
                    InternalQueryExpression qe      =   new InternalQueryExpression();
                    qe.ColumnSet                    =   new InternalAllColumns();
                    qe.EntityName                   =   PStr.projectitem;
                    qe.Criteria                     =   new InternalFilterExpression();
                    InternalConditionExpression ce  =   new InternalConditionExpression();
                    ce.Operator                     =   InternalConditionOperator.Equal;
                    ce.AttributeName                =   PStr.callingprofile;
                    ce.Values                       =   new string[]{CallingProfile.ToString()};
                    qe.Criteria.FilterOperator      =   InternalLogicalOperator.And;
                    qe.Criteria.Conditions          =   new InternalConditionExpression[]{CRMUtil.StateCodeIsActiveCondition,ce};
                    _PItemLst                       =   Wrapper.Util.FindEntitiesByQuery<ADNDynProjectItem>(qe,ResetWrapper,ref SelectedGuid);
                    Cache2.InsertMinutes(CKey,_PItemLst,CacheDelay);
			        if (InterviewTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]InterviewUtil GetAllProjectItems _PItemLst.Count: {0}",_PItemLst.Count),InterviewTrace.Sw.Info);
                }
                InternalQueryExpression qe2         =   new InternalQueryExpression();
                qe2.ColumnSet                       =   new InternalAllColumns();
                qe2.EntityName                      =   PStr.projectitemvalue;
                qe2.Criteria                        =   new InternalFilterExpression();
                InternalConditionExpression ce2     =   new InternalConditionExpression();
                ce2.Operator                        =   InternalConditionOperator.Equal;
                ce2.AttributeName                   =   PStr.interviewid;
                ce2.Values                          =   new string[]{InterviewId.ToString()};
                qe2.Criteria.FilterOperator         =   InternalLogicalOperator.And;
                qe2.Criteria.Conditions             =   new InternalConditionExpression[]{CRMUtil.StateCodeIsActiveCondition,ce2};
                _PValuesList                        =   Wrapper.Util.FindEntitiesByQuery<ADNDynProjectItemValue>(qe2,ResetWrapper,ref SelectedGuid);
			    if (InterviewTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]InterviewUtil GetAllProjectItems _PValuesList.Count: {0}",_PValuesList.Count),InterviewTrace.Sw.Info);

                _cSettings                          =   new SettingsDictionary();
                foreach ( string key in _PItemLst.Keys )
                {
                    string key2                     =   key.ToUpper(CultureInfo.InvariantCulture).Replace(' ','_').Replace('\'','_');
			        if (InterviewTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]InterviewUtil GetAllProjectItems inserting key: {0}, key2: {1}",key,key2),InterviewTrace.Sw.Info);
                    ADNDynProjectItem dynpi         =   _PItemLst[key];
                    int dataType                    =   dynpi.datatype;
                    SettingItem item                =   null;
			        if (InterviewTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]InterviewUtil GetAllProjectItems inserting dataType: {0}, projecttype: {1}, values: '{2}'",
                            dataType,dynpi.projecttype,dynpi.values),InterviewTrace.Sw.Info);
                    switch(dataType)
                    {
                        case 1: // string
                        item                        =    new SettingItem(key2,new StringDataType());
                        break;

                        case 2: // bool
                        item                        =    new SettingItem(key2,new BooleanDataType());
                        break;

                        case 3: // integer
                        item                        =    new SettingItem(key2,new IntegerDataType());
                        break;

                        case 4: // picklist
                        item                        =    new SettingItem(key2,new ListDataType(dynpi.values));
                        break;

                        case 5: // datetime
                        item                        =    new SettingItem(key2,new DateDataType());
                        break;

                        case 6: // money
                        item                        =    new SettingItem(key2,new MoneyDataType());
                        break;

                        case 7: // memo
                        StringDataType memo         =   new StringDataType();
                        memo.NbLines                =   3;
                        item                        =   new SettingItem(key2,memo);
                        break;

                        case 8: // lookup
                        string entName              =    dynpi.values;
                        try
                        {
                            WSListDataType ws       =   new WSListDataType(entName,StStr.smName,StStr.bgID);
                            item                    =   new SettingItem(key2,ws);
                        }
                        catch // bad entity for wsListDataType
                        {
                            StringDataType badItem  =   new StringDataType("Bad entity for lookup");
                            item                    =   new SettingItem(key2,badItem);
                            item.ReadOnly           =   true;
                        }

                        break;
                        
                        default:
                        continue;
                    }
                    item.Order                      =   dynpi.order;
                    item.Description                =   dynpi.description;
                    item.EnglishName                =   dynpi.name;
                    item.Group                      =   (SettingItemGroup)((int)SettingItemGroup.CUSTOM_USER_SETTINGS+dynpi.projecttype*1000);
                    if ( !SettingItemGroups.AllGroups.ContainsKey((int)item.Group) )
                        SettingItemGroups.AllGroups.Add((int)item.Group,dynpi.projecttypeLabel);

                    if ( _PValuesList.ContainsKey(key) )
                    {
                        string val                  =   _PValuesList[key].value;
			            if (InterviewTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]InterviewUtil GetAllProjectItems setting value key: {0}, val: {1}",key,val),InterviewTrace.Sw.Info);
                        if ( !string.IsNullOrEmpty(val) || ( dataType == 1 ) )
                            item.Value              =   val;
                    }
                    else
                    {
                        if ( dynpi.values != string.Empty )
                        {
                            if ( dataType != 8 ) 
                            {
                                if ( dataType != 4 )
                                    item.Value          =   dynpi.values;
                                else 
                                {
                                    string[]vals        =   dynpi.values.Split(new char[]{';'},StringSplitOptions.RemoveEmptyEntries);
                                    item.Value          =   vals[0];
                                }
                            }
                        }
                    }
                    if ( InterviewId == Guid.Empty )
                        item.ReadOnly               =   true;
                    _cSettings.Add(key2,item);
                }
		        if (InterviewTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]InterviewUtil GetAllProjectItems END inserting cSettings.Count: {0}",_cSettings.Count),InterviewTrace.Sw.Info);
            }
            catch(Exception ex)
            {
		        if (InterviewTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]InterviewUtil GetAllProjectItemsex: {0}",ex),InterviewTrace.Sw.Info);
                throw;
            }
            return _cSettings;
        }

    }
}
